package com.dl.ycq.framework.datasource.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.dl.ycq.framework.datasource.DataSourceName;
import com.dl.ycq.framework.datasource.bean.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSourceConfig {

    /**
     * 创建 DataSource Bean
     */
    @Bean
    @ConfigurationProperties("spring.datasource.druid.one")
    public DataSource oneDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.two")
    public DataSource twoDataSource() {
        return DruidDataSourceBuilder.create().build();
    }



    /**
     * 如果还有数据源,在这继续添加 DataSource Bean
     */
    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource oneDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(1);
        targetDataSources.put(DataSourceName.ONE.getDataSourceName(), oneDataSource());
        targetDataSources.put(DataSourceName.TWO.getDataSourceName(), twoDataSource());

        // 还有数据源,在targetDataSources中继续添加
        return new DynamicDataSource(oneDataSource, targetDataSources);
    }
}
